package com.qihetimes.earthangel.config;

import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.qihetimes.earthangel.common.ResponseResult;
import com.qihetimes.earthangel.common.annotation.NoLogin;
import com.qihetimes.earthangel.model.User;
import com.qihetimes.earthangel.service.IUserService;
import com.qihetimes.earthangel.service.impl.RedisService;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 登录拦截器
 *
 * @author ：f4cklangzi@gmail.com
 * @date ：Created At 2021/12/10
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    
    @Resource
    private RedisService redisService;
    
    @Resource
    private IUserService userService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            writeError(response, HttpStatus.NOT_FOUND, "资源未找到!");
            return false;
        }
        HandlerMethod method = (HandlerMethod) handler;
        NoLogin noLogin = method.getMethodAnnotation(NoLogin.class);
        if (noLogin != null) {
            return true;
        }
        String token = request.getHeader("Authorization");
        if (token == null) {
            writeError(response, HttpStatus.UNAUTHORIZED, "未登录!");
            return false;
        }
        String userId = (String) redisService.get(token);
        if (userId == null) {
            writeError(response, HttpStatus.UNAUTHORIZED, "登录过期，请重新登录!");
            return false;
        }
        User user = userService.getById(userId);
        if (user == null) {
            redisService.remove(token);
            writeError(response, HttpStatus.UNAUTHORIZED, "用户不存在!");
            return false;
        }
        request.setAttribute("user", user);
        return true;
    }
    
    private void writeError(HttpServletResponse response, HttpStatus status, String msg) throws IOException {
        response.setContentType(ContentType.JSON.getValue());
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        ServletOutputStream outputStream = response.getOutputStream();
        ResponseResult<Object> result = ResponseResult.failed(status, msg);
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
